package com.ai.api.controller;

import com.ai.api.config.MinIOConfig;
import com.ai.api.config.MinIOUtils;
import com.ai.grace.result.GraceJSONResult;
import com.ai.grace.result.ResponseStatusEnum;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mapping.IdentifierAccessor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileController {
    @Autowired
    private MinIOConfig minIOConfig;

    /**
     * 上传面试官图片
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("uploadInterviewerImage")
    public GraceJSONResult uploadInterviewerImage(@RequestParam("file")MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }
        filename="interviewer/"+ dealWithoutFileName(filename);
        String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(), filename, file.getInputStream(), true);
        return GraceJSONResult.ok(imageUrl);
    }

    @PostMapping("uploadInterviewVideo")
    public GraceJSONResult uploadInterviewVideo(@RequestParam("file")MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }
        filename="interviewVideo/"+ dealWithoutFileName(filename);
        String videoUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(), filename, file.getInputStream(), true);
        return GraceJSONResult.ok(videoUrl);
    }

    /**
     * 处理图片名字
     * @param filename
     * @return
     */
    private String dealWithoutFileName(String filename){
        String suffixName = filename.substring(filename.lastIndexOf("."));
        if (suffixName.equals(".jpg")){
            System.out.println("********"+suffixName);
            suffixName = ".jpeg";
        }
        String uuid = UUID.randomUUID().toString();
        return uuid+suffixName;
    }
}
